package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Transactional(rollbackFor = Exception.class)
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Resource
    private DepartmentRepository departmentRepository;

    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        // 把参数map集合 ---> JSON字符串  | JSON字符串  --->  为Java对象
        String stringMap = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(stringMap, Department.class);
        // 查询mogodb的数据,判断是否存在数据
        Department targetDepartment =
                departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        // 如果不存在, 进行添加
        if (null != targetDepartment) {
            BeanUtils.copyProperties(targetDepartment, department);
            departmentRepository.save(department);
        } else {
            // 如果存在, 进行修改
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> findDepartmentPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        // 分页处理
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(page = 1, limit, sort);
        // 创建实体对象进行参数介绍
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        // 创建匹配器,也就是如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        // 创建实例查询
        Example<Department> example = Example.of(department, matcher);

        // 调用查询方法
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public void removeDepartmentByHashcodeAndDecade(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        department.setCreateTime(new Date());
        department.setIsDeleted(1);
        if (ObjectUtils.isEmpty(department)) {
            departmentRepository.save(department);
        } else {
            departmentRepository.save(department);
        }


    }

    /**
     * 查询医院所有科室列表
     *
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> getDepartmentListByHoscode(String hoscode) {
        // 创建集合用于封装数据
        List<DepartmentVo> resultList = new ArrayList<>();

        // 根据医院编号,查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example example = Example.of(departmentQuery);
        // 查询所有科室
        List<Department> departmentList = departmentRepository.findAll(example);
        // 根据大的科室编号,bigcode分组,获取每个大的科室下面的子科室
        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        // 遍历集合departmentMap
        // departmentMap.forEach((k, v) -> { System.out.println("k = " + k + " v =" + v);});
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            // 大的科室的编号
            String bigcode = entry.getKey();
            // 大的科室对应的全局的编号
            List<Department> departmentList1 = entry.getValue();

            // 封装大的科室
            DepartmentVo departmentVoBig = new DepartmentVo();
            departmentVoBig.setDepcode(bigcode);
            departmentVoBig.setDepname(departmentList1.get(0).getBigname());
            //departmentVoBig.setDepname(departmentList1.get(0).getDepname()); // todo: 这里封装有问题

            // 封装小科室
            List<DepartmentVo> childrenOfDepartmentVoBig = new ArrayList<>();
            departmentList1.forEach(department -> {
                DepartmentVo departmentVoSmall = new DepartmentVo();
                departmentVoSmall.setDepcode(department.getDepcode());
                departmentVoSmall.setDepname(department.getDepname());
                // 添加到childrens集合
                childrenOfDepartmentVoBig.add(departmentVoSmall);
            });

            // 把小科室集合放到大科室里面
            departmentVoBig.setChildren(childrenOfDepartmentVoBig);

            // 最终添加到departmentVoList集合进行封装
            resultList.add(departmentVoBig);
        }

        // 返回查询结果集
        return resultList;
    }

    @Override
    public String getDepNameByHoscodeAndDepcode(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (ObjectUtils.isEmpty(department)) {
            return "查无此门";
        }

        return department.getDepname();
    }

    @Override
    public Department getDepartmentByHoscodeAndDepcode(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (ObjectUtils.isEmpty(department)) {
            return null;
        }
        return department;
    }


}
